import { Button, Tabs, View, Text, List, WhiteSpace, DatePicker } from 'antd-mobile';
import React, { Component } from 'react';
import { AppRegistry, ScrollView, FlatList } from 'react-native';

import { ItemTemperChart } from './ItemTemperChart'
import { Urls } from '../../../utils/Urls';

import { NavigationActions } from 'react-navigation'
const loginAction = NavigationActions.reset({
    index: 0,
    actions: [
        NavigationActions.navigate({ routeName: 'LoginScreen', params: { token: '123456' } })
    ]
})

const nowTimeStamp = Date.now();
const start = nowTimeStamp - 24*60*60*1000;
const now = new Date(nowTimeStamp);
function formatDate(date) {
    /* eslint no-confusing-arrow: 0 */
    
    const pad = n => n < 10 ? `0${n}` : n;
    const dateStr = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
    const timeStr = `${pad(date.getHours())}:${pad(date.getMinutes())}`;
    return `${dateStr} ${timeStr}`;
}
export class ItemHistoryScreen extends Component {
    static navigationOptions = ({ navigation }) => ({
        headerTitle: navigation.state.params.title,
        headerTitleStyle: { alignSelf: 'center' }
    });
    constructor(props) {
        super(props)
        this.state = {
            startDate: new Date(start),
            endDate: now,
            temperHistory: [],
            keys: [],
            data: []
        }
    }
    
    getData = (start, end) => {
        let url = Urls.MONITOR_LIST + "?id=" + this.props.navigation.state.params.id;
        console.log("请求单个测温设备的历史数据：" + url)

        if (start == null || start == "undefined") {
            start = formatDate(this.state.startDate)
        } else {
            start = formatDate(start)
        }
        if (end == null || end == "undefined") {
            end = formatDate(this.state.endDate)
        } else {
            end = formatDate(end)
        }

        
        console.log(`${url}&start_time=${start}&end_time=${end}&type=0`);
        
        fetch(`${url}&start_time=${start}&end_time=${end}&type=0`, {
            method: 'GET',
            headers: {
                'Content-Type': 'multipart/x-www-form-urlencoded',
            }
        }).then(response => response.json())
            .then(resData => {
                
                if (resData.code == 0) {
                    let temperHistory = resData.content
                    let keys = [], data = []
                    temperHistory.forEach(element => {
                        keys.push(element.create_time)
                        data.push(element.temperature)
                    });
                    this.setState({
                        temperHistory: temperHistory,
                        keys: keys,
                        data: data
                    })
                } else  if (resData.code == 1) {
                    Toast.fail('登录过期，重新登录', 1);
                    this.props.navigation.dispatch(loginAction)
                }
            })
            .catch((error) => {
                console.log(error);
            })
    }
    componentDidMount() {
        this.getData();
    }
    render() {
        
        const tab = [
            { title: '历史温度趋势棒图' },
            { title: '历史数据' }
        ];
        return (
            <ScrollView>
                <WhiteSpace size="sm" />
                <List className="date-picker-list" style={{ backgroundColor: 'white' }}>
                    <DatePicker
                        value={this.state.startDate}
                        format="YYYY-MM-DD HH:mm"
                        onChange={date => 
                            {
                                
                                console.log("日期：", formatDate(date));
                                
                                this.setState({ startDate: date })
                                this.getData(date)
                            }
                        }
                        // onOk={this.getData()}
                    >
                        <List.Item arrow="horizontal">查询开始时间</List.Item>
                    </DatePicker>
                    <DatePicker
                        value={this.state.endDate}
                        onChange={date => 
                            {
                                this.setState({ startDate: date })
                                this.getData(null, date)
                            }
                        }
                        // onOk={this.getData()}
                    >
                        <List.Item arrow="horizontal">查询结束时间</List.Item>
                    </DatePicker>
                </List>
                <WhiteSpace size="sm" />
                <Tabs tabs={tab}>
                    <ScrollView>
                        <ItemTemperChart keys={this.state.keys} data2={this.state.data}></ItemTemperChart>
                    </ScrollView>

                    <ScrollView>
                        <WhiteSpace />
                        <FlatList
                            data={this.state.temperHistory}
                            renderItem={({ item, index }) => <List.Item key={index}
                                onClick={() => navigate('ItemHistoryScreen', { id: item.id })}
                                extra={item.create_time}
                            >{item.temperature + "℃"}</List.Item>}
                            onEndReached={this._onEndReached}
                        />
                    </ScrollView>
                </Tabs>
            </ScrollView>
        );
    }
    _onEndReached = () => {
        // this.setState((state) => ({
        //   data: state.data.concat(genItemData(100, state.data.length)),
        // }));
        console.log("到底部了")
    };
    
}